# -*- coding: utf-8 -*-
# Description: Flask应用
# Created: dingwenjing 2022/11/29

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

from app.task.make_celery import make_celery
from app.util.actuator import Actuator
from app.util.core import JSONEncoder
from config import config, Config

# SQLAlchemy数据库访问实例
db = SQLAlchemy()
from app.util.aspect import *


def _access_control(response):
    """解决跨域请求

    :param response:
    :return:
    """
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = (
        'GET,HEAD,PUT,PATCH,POST,DELETE')
    response.headers['Access-Control-Allow-Headers'] = 'Content-Type'
    response.headers['Access-Control-Max-Age'] = 86400
    return response


def create_app(config_name):
    """根据环境配置名称，创建Flask应用。

    :param config_name: 环境配置名称
    :return: app Flask应用
    """
    # __name__ 当前模块名称
    app_name = getattr(Config, 'APP_NAME', __name__)
    app = Flask(app_name)

    # 初始化app配置
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    # 返回json格式转换
    app.json_encoder = JSONEncoder

    # 解决跨域
    app.after_request(_access_control)

    # 数据库连接初始化
    if app.config.get('SQLALCHEMY_DATABASE_URI'):
        # print(app.config.get('SQLALCHEMY_DATABASE_URI'))
        db.init_app(app)
        print(app.config['SQLALCHEMY_DATABASE_URI'])
    else:
        print('false')

    # 初始化蓝本(路由)
    from .main import blueprint
    app.register_blueprint(blueprint, url_prefix='')

    # 初始化应用监控
    Actuator.init_app(app)

    # 初始化celery
    make_celery(app)
    return app
